//
//  DDRegisterViewController.m
//  ialone
//
//  Created by 陆翀 on 16/1/16.
//  Copyright © 2016年 JasperSong. All rights reserved.
//

#import "DDRegisterViewController.h"
#import "DDRegisterView.h"
#import "UMSocialSnsPlatformManager.h"
#import "UMSocialAccountManager.h"
#import "FMDB.h"
#import "DDManager.h"
@interface DDRegisterViewController () <UITextFieldDelegate>
@property (nonatomic,strong)FMDatabase *db;
@property (nonatomic,assign)BOOL isrename;
@end

@implementation DDRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _isrename = NO;
    self.navigationController.navigationBarHidden = YES;
    
    
    self.titleLabel.text = @"注册";
    self.titleLabel.font = [UIFont systemFontOfSize:25];
    
    [self.leftButton addTarget:self action:@selector(leftButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.leftButton setImage:[UIImage imageNamed:@"item_cancel@2x"] forState:(UIControlStateNormal)];
    
    // 登录状态
    DDRegisterView *registerView = [[DDRegisterView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64)];
    registerView.backgroundColor = [UIColor whiteColor];
    
    registerView.phoneNumberTF.placeholder = @" 用户名";
    registerView.phoneNumberTF.delegate = self;
    registerView.phoneNumberTF.clearsOnBeginEditing = YES;
    registerView.phoneNumberTF.clearButtonMode = UITextFieldViewModeUnlessEditing;
    registerView.phoneNumberTF.tag = 1001;
    
//    [registerView.securityCodeButton setTitle:@"点此验证" forState:(UIControlStateNormal)];
//    [registerView.securityCodeButton setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
//    [registerView.securityCodeButton addTarget:self action:@selector(securityCodeButton:) forControlEvents:(UIControlEventTouchUpInside)];
    
    registerView.passwordTF.placeholder = @" 密码";
    registerView.passwordTF.delegate = self;
    registerView.passwordTF.clearsOnBeginEditing = YES;
    registerView.passwordTF.clearButtonMode = UITextFieldViewModeUnlessEditing;
    registerView.passwordTF.tag = 1002;
    
    [self.view addSubview:registerView];
   // self.navigationItem.title = @"注册";
    
    // 注册协议
    registerView.userSgreementLable.text = @"完成并注册,表示你已阅读并同意";
    registerView.userSgreementLable.font = [UIFont systemFontOfSize:13];
    [registerView.userSgreementButton setTitle:@"单读用户协议" forState:(UIControlStateNormal)];
    registerView.userSgreementButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [registerView.userSgreementButton setTitleColor:[UIColor brownColor] forState:(UIControlStateNormal)];
    [registerView.userSgreementButton addTarget:self action:@selector(user:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [registerView.loginButton setTitle:@"注册" forState:UIControlStateNormal];
    [registerView.loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [registerView.loginButton addTarget:self action:@selector(loginButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerView];
    [registerView.sinaLoginButton addTarget:self action:@selector(sinaLoginButton:) forControlEvents:UIControlEventTouchUpInside];
    [registerView.weiXinLoginButton addTarget:self action:@selector(weiXinLoginButton:) forControlEvents:UIControlEventTouchUpInside];
    //创建我们的数据库的路径,同时拼接数据库名字
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"DDDataBase.db"];
    NSLog(@"%@",path);
    //根据路径去创建一个数据库
    _db = [FMDatabase databaseWithPath:path];
    //调用open方法打开数据库,成功返回YES,失败返回NO
    if ([_db open]) {
        NSLog(@"打开成功");
    }else
    {
        NSLog(@"打开失败");
    }
    //调用db的executeUpdate,这个方法的参数就是sql语句.
    [_db executeUpdate:@"CREATE TABLE UserList (username text, password text)"];
    
    
}
-(void)loginButton:(UIButton *)button
{
    UITextField *textfield1 = (UITextField *)[self.view viewWithTag:1001];
    UITextField *textfield2 = (UITextField *)[self.view viewWithTag:1002];
    if (textfield1.text.length != 0 && textfield2.text.length != 0) {
        //执行查找的操作,调用的方法是executeQuery,参数是sql的查找语句,会返回一个FMResultSet类型的结果
        FMResultSet *result = [_db executeQuery:@"SELECT username FROM UserList"];
        while ([result next]) {
            NSString *username = [result stringForColumn:@"username"];
            if ([textfield1.text isEqualToString:username]) {
                UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"用户名已存在" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
                [alter show];
                [UIView animateWithDuration:1 animations:^{
                    [alter dismissWithClickedButtonIndex:0 animated:YES];
                }];
                _isrename = YES;
            }
        }
        if (_isrename == NO) {
            //FMDB插入的时候必须是个对象如果表里面一个字段是int类型,插入的时候需要插入一个NSNumber对象
            [_db executeUpdate:@"INSERT INTO UserList (username,password) values(?,?)",textfield1.text,textfield2.text];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"注册成功" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
            [alter show];
            [UIView animateWithDuration:1 animations:^{
                [alter dismissWithClickedButtonIndex:0 animated:YES];
            }];
            [self.navigationController popViewControllerAnimated:YES];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"islogin"];
            [[NSUserDefaults standardUserDefaults] setValue:textfield1.text forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
        
    }else
    {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"内容不能为空" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
        [alter show];
        [UIView animateWithDuration:1 animations:^{
            [alter dismissWithClickedButtonIndex:0 animated:YES];
        }];
    }
}
-(void)sinaLoginButton:(UIButton *)button
{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        //          获取微博用户名、uid、token等
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            
            FMResultSet *result = [_db executeQuery:@"SELECT username FROM UserList"];
            while ([result next]) {
                NSString *username = [result stringForColumn:@"username"];
                if ([snsAccount.userName isEqualToString:username]) {
                    UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"用户名已存在" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
                    [alter show];
                    [UIView animateWithDuration:1 animations:^{
                        [alter dismissWithClickedButtonIndex:0 animated:YES];
                    }];
                    _isrename = YES;
                }
            }
            if (_isrename == NO) {
                //FMDB插入的时候必须是个对象如果表里面一个字段是int类型,插入的时候需要插入一个NSNumber对象
                [_db executeUpdate:@"INSERT INTO UserList (username,password) values(?,?)",snsAccount.userName,snsAccount.unionId];
                UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"注册成功" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
                [alter show];
                [UIView animateWithDuration:1 animations:^{
                    [alter dismissWithClickedButtonIndex:0 animated:YES];
                }];
                [self.navigationController popViewControllerAnimated:YES];
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"islogin"];
                [[NSUserDefaults standardUserDefaults] setValue:snsAccount.userName forKey:@"username"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }

        }});
    [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToSina  completion:^(UMSocialResponseEntity *response){
        NSLog(@"SnsInformation is %@",response.data);
    }];
}
-(void)weiXinLoginButton:(UIButton *)button
{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        //          获取微博用户名、uid、token等
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQQ];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            FMResultSet *result = [_db executeQuery:@"SELECT username FROM UserList"];
            while ([result next]) {
                NSString *username = [result stringForColumn:@"username"];
                if ([snsAccount.userName isEqualToString:username]) {
                    UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"用户名已存在" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
                    [alter show];
                    [UIView animateWithDuration:1 animations:^{
                        [alter dismissWithClickedButtonIndex:0 animated:YES];
                    }];
                    _isrename = YES;
                }
            }
            if (_isrename == NO) {
                //FMDB插入的时候必须是个对象如果表里面一个字段是int类型,插入的时候需要插入一个NSNumber对象
                [_db executeUpdate:@"INSERT INTO UserList (username,password) values(?,?)",snsAccount.userName,snsAccount.unionId];
                UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"注册成功" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
                [alter show];
                [UIView animateWithDuration:1 animations:^{
                    [alter dismissWithClickedButtonIndex:0 animated:YES];
                }];
                [self.navigationController popViewControllerAnimated:YES];
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"islogin"];
                [[NSUserDefaults standardUserDefaults] setValue:snsAccount.userName forKey:@"username"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }});
    [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToQQ  completion:^(UMSocialResponseEntity *response){
        NSLog(@"SnsInformation is %@",response.data);
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)user:(UIButton *)button
{
    UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"欢迎使用" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [alter show];
    [UIView animateWithDuration:1 animations:^{
        [alter dismissWithClickedButtonIndex:0 animated:YES];
    }];
}

// 点此验证
//- (void)securityCodeButton:(UIButton *)sender
//{
//    NSLog(@"2");
//}
- (void)leftButton:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}


// 键盘回弹
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITextField *textfield1 = (UITextField *)[self.view viewWithTag:1001];
    [textfield1  resignFirstResponder];
    UITextField *textfield2 = (UITextField *)[self.view viewWithTag:1002];
    [textfield2  resignFirstResponder];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
